"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机在事务中在事务中执行调用函数
Create At   : 2023/07/11
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建包含DDL语句的函数
    3.备机在事务中执行调用函数
    4.创建只用DML语句的函数
    5.创建表，并且在备机事务中执行调用函数
    6.备机查看日志打印
    7.环境清理，恢复参数
Expect      :
    1.修改成功
    2.创建成功
    3.执行失败，不支持事务中的DDL
    4.创建成功
    5.执行成功
    6.日志记录建立连接、转发给主机、接受执行结果等libpqsw信息
    7.环境清理成功，恢复参数成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table_name = 't_multi_node_write_0032'
        self.function_name_1 = 'func_multi_node_write_0032_1'
        self.function_name_2 = 'func_multi_node_write_0032_2'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_multi_node_write0032')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_dir, f'执行失败:{step1}')

        step2 = "-----step2:创建包含DDL语句的函数;expect:创建成功-----"
        self.logger.info(step2)
        ddl_cmd = f'''create or replace function {self.function_name_1}
            (tb_name varchar) return varchar is 
            begin 
                execute immediate 'drop table if exists  ' || tb_name || ';';
                execute immediate 'create table  '|| tb_name || 
                '(id int, name varchar(20));';
                end;'''
        create_msg = self.standby_sh.execut_db_sql(ddl_cmd)
        self.logger.info(create_msg)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG,
                      create_msg, f'执行失败:{step2}')
        time.sleep(2)

        step3 = "-----step3:备机在事务中执行调用函数;expect:执行失败-----"
        self.logger.info(step3)
        sql_cmd = f'''start transaction;
                    call {self.function_name_1}('{self.table_name}');
                    end;'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.function_name_1, sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.ROLLBACK_MSG, sql_msg,
                      f'执行失败:{step3}')
        self.assertIn("ERROR", sql_msg, f'执行失败:{step3}')

        step4 = '-----stpe4:创建只有DML语句的函数;expect:创建成功----'
        self.logger.info(step4)
        dml_cmd = f'''create or replace function {self.function_name_2}
            (tb_name varchar) return varchar is 
            begin
                execute immediate 'insert into ' || tb_name ||
                ' values (generate_series(1,10), ''test'');';
                execute immediate 'update ' || tb_name ||
                ' set name=''software'' where id = 3;';
                execute immediate 'delete from ' || tb_name || ' where id = 5;';
                return tb_name;
                end;'''
        create_msg = self.standby_sh.execut_db_sql(dml_cmd)
        self.logger.info(create_msg)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG,
                      create_msg, f'执行失败:{step4}')
        time.sleep(2)

        step5 = "-----step5:备机在事务中在事务中执行调用函数;expect:执行成功-----"
        self.logger.info(step5)
        sql_cmd = f'''drop table if exists {self.table_name};
            create table {self.table_name} (id int, name varchar(20));
            start transaction;
            call {self.function_name_2}('{self.table_name}');
            end;
            select pg_sleep(30);
            select * from {self.table_name};'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step5}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step5}')
        self.assertIn(self.function_name_2, sql_msg, f'执行失败:{step5}')
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, sql_msg,
                      f'执行失败:{step5}')
        self.assertNotIn("ERROR", sql_msg, f'执行失败:{step5}')
        self.assertIn("  1 | test\n  2 | test\n  4 | test\n  6 | test\n  "
                      "7 | test\n  8 | test\n  9 | test\n 10 | test\n  "
                      "3 | software", sql_msg, f'执行失败:{step5}')
        time.sleep(2)

        step6 = "-----step6:备机查看日志打印;expect:日志记录建立连接、" \
                "转发给主机、接受执行结果等libpqsw信息-----"
        self.logger.info(step6)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('transaction status change',
                      shell_msg, f'执行失败:{step6}')
        self.assertIn('Connecting to remote server',
                      shell_msg, f'执行失败:{step6}')
        self.assertIn(f'LOG:  libpqsw', shell_msg, f'执行失败:{step6}')

    def tearDown(self):
        step7 = "-----step7:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step7)
        drop_cmd = f"drop function if exists {self.function_name_1};" \
                   f"drop function if exists {self.function_name_2};" \
                   f"drop table if exists {self.table_name};"
        drop_msg = self.standby_sh.execut_db_sql(drop_cmd)
        self.logger.info(drop_msg)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.logger.info("-----断言teardown-----")
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG,
                      drop_msg, f'执行失败:{step7}')
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_msg, f'执行失败:{step7}')
        self.assertTrue(result1, f'执行失败:{step7}')
        self.assertTrue(restart_res, f'执行失败:{step7}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step7}')
        self.assertTrue(result2, f'执行失败:{step7}')
        self.assertTrue(result3, f'执行失败:{step7}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step7}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step7}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
